package com.tools.cleanmaster.taskmain;

import android.app.ActivityManager;
import android.content.Context;
import android.os.SystemClock;

import com.tools.cleanmaster.utils.PackageUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;


/**
 * Created by lianzhan on 16/1/12.
 */
public class TKPubApi {
        /**
     * Get running processes.
     *
     * @param cxt
     * @param needIconLabel If true, {@link ProcessItem#icon} and {@link ProcessItem#label} are available.
     * @return If no running processes, an empty ArrayList will be returned.
     * @note {@link ProcessItem#pkgName} and {@link ProcessItem#pids}
     * and {@link ProcessItem#sys} are always available.
     */
    public static ArrayList<ProcessItem> getRunningProcesses(Context cxt,
                                                             boolean needIconLabel) {
        HashMap<String, ProcessItem> map = new HashMap<String, ProcessItem>();
        ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
        AppTaskUtils.getRunningTaskList(cxt, am, map, needIconLabel, true, null);
        ArrayList<ProcessItem> result = new ArrayList<ProcessItem>();
        for (ProcessItem item : map.values()) {
            if (item.checked) {
                result.add(item);
            }
        }
        return result;
    }

    public static ArrayList<ProcessItem> getRunningSortProcesses(Context cxt, boolean needIconLabel) {
        ArrayList<ProcessItem> result = getRunningProcesses(cxt, needIconLabel);
        if (result != null) {
            Collections.sort(result);
        }
        return result;
    }

    public static void killProcesses(Context context, List<ProcessItem> processes,
                                     ArrayList<String> packageNames) {
        for (ProcessItem item : processes) {
            if (packageNames != null && packageNames.contains(item.pkgName)) {
                continue;
            }
            PackageUtils.killPackage(context, item.pkgName);
        }
        // force sleep 500 ms for make system release all memory
        SystemClock.sleep(500);
    }

}
